package com.qf.chinatelcon.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.chinatelcon.apigateway.cache.PublicParamsLocalCache;
import com.qianfeng.smsplatform.common.constants.InterfaceExceptionDict;
import com.qianfeng.smsplatform.common.exceptions.MyBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Component
public class PublicParamsFilter extends ZuulFilter {

    private PublicParamsLocalCache publicParamsLocalCache;

    @Autowired
    public void setPublicParamsLocalCache(PublicParamsLocalCache publicParamsLocalCache) {
        this.publicParamsLocalCache = publicParamsLocalCache;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 10;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        return context.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        List<String> paramsList = publicParamsLocalCache.getAllNeedParamsList();//获取到所有的参数名称
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        try {
            paramsList.forEach(name -> {
                String parameter = request.getParameter(name);
                if (ObjectUtils.isEmpty(parameter)) {
                    context.setSendZuulResponse(false);//拦截，不让他往下执行
                    throw new MyBaseException("参数：" + name + "没有传递值", InterfaceExceptionDict.RETURN_STATUS_PUBLICPARAMS_ERROR);

                }
            });
        } catch (Exception e) {
            context.addZuulResponseHeader("content-Type", "text/html;charset=utf-8");
            context.setResponseBody(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
